#pragma once
#include <iostream>
#include <string>
#include <string.h>
#include "Log.hpp"
#include "Init.hpp"

extern Log log;
Init init;

class Task
{
public:
    Task(int sockfd, const std::string &clientip, const uint16_t &clientport)
        : _sockfd(sockfd), _clientip(clientip), _clientport(clientport)
    {
    }
    Task()
    {
    }
    void run()
    {
        char buffer[4096];
        // Tcp是面向字节流的，你怎么保证，你读取上来的数据，是"一个" "完整" 的报文呢？
        ssize_t n = read(_sockfd, buffer, sizeof(buffer)); // BUG?
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client key# " << buffer << std::endl;
            std::string echo_string = init.translation(buffer); // 执行翻译任务，该操作由线程池执行
            // echo_string += buffer; //对话打开，翻译去掉

            int n = write(_sockfd, echo_string.c_str(), echo_string.size()); // 写的时候万一对应的客户端断开连接了，那么写会崩溃
            if (n < 0)
            {
                log(Warning, "write error, errno: %d, errstring: %s", errno, strerror);
            }
        }
        else if (n == 0)
        {
            log(Info, "%s:%d quit, server close sockfd: %d", _clientip.c_str(), _clientport, _sockfd);
        }
        else
        {
            log(Warning, "read error, sockfd: %d, client ip: %s, client port: %d", _sockfd, _clientip.c_str(), _clientport);
        }
        close(_sockfd);
    }
    void operator()()
    {
        run();
    }
    ~Task()
    {
    }

private:
    int _sockfd;
    std::string _clientip;
    uint16_t _clientport;
};